<?php

namespace app\yy\services;

use app\yy\model\Images as ImgModel;
use app\yy\model\Website as WebModel;

class Wordpress extends BaseService
{


    public function multiCurlPost($post_data_array)
    {
        // 初始化 cURL 批处理句柄
        $mh = curl_multi_init();

        // 初始化 cURL 句柄数组
        $ch_array = array();

        foreach ($post_data_array as $post_data) {
            $url = $post_data['url'];
            $data = $post_data['data'];

            // 初始化 cURL 句柄
            $ch = curl_init();

            // 设置 cURL 选项
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

            // 将 cURL 句柄添加到 cURL 批处理句柄
            curl_multi_add_handle($mh, $ch);

            // 将 cURL 句柄存储到数组中
            $ch_array[] = $ch;
        }

        // 执行所有 cURL 请求
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);


        // 获取所有请求结果
        $results = array();


        foreach ($ch_array as $ch) {
            $result = curl_multi_getcontent($ch);
            $results[] = $result;

            // 关闭 cURL 句柄
            curl_multi_remove_handle($mh, $ch);
            curl_close($ch);
        }

        // 关闭 cURL 批处理句柄
        curl_multi_close($mh);

        // 返回所有请求结果
        return $results;
    }


    public function yyToWordpress($info, $category, $options, $products)
    {
        // 记录程序开始时间
        $startTime = microtime(true);

        $images_list = ImgModel::where('website_id', $info['id'])->select();

        $new_image_list = [];

        foreach ($images_list as $item) {



            $new_image_list[$item['sku']][$item['rank']] = $item['oss_image'];

        }


        $all_cates = $category;

        // 插入商品

        $all_products = $products;


        foreach ($all_products as &$pro) {
            $images = !empty($new_image_list[$pro['sku']]) ? $new_image_list[$pro['sku']] : [];


            $pro['main_image'] = !empty($images[0]) ? $images[0] : '';

            if (!empty($images[0])) {
                unset($images[0]);
            }

            $add_attached_images = $images;


            $pro['add_attached_images'] = $add_attached_images;

            $attributes = [];

            if (!empty($pro['options'])) {

                foreach ($pro['options'] as $op) {

                    if (!empty($op['option_name']) && !empty($op['option_value_old'])) {
                        $attributes[$op['option_name']] = $op['option_value_old'];
                    }

                }

            }

            $pro['options'] = $attributes;

        }


        // 指定每个块的大小
        $chunk_size = 10;

        $all_products_list = array_chunk($all_products, $chunk_size);

        $post_url = 'https://' . $info['domain'] . '?using_import_product=nNFrUJIh6gmplLMQ';

        $success_count = 0;

        $max_curl = 50;
        $new_curl = 0;

        $curl_data = [];

        $chu_count = count($all_products_list);

        foreach ($all_products_list as $k_chu => $chu) {

            if ($success_count == 0) {

                $post_data = [
                    'all_cates' => base64_encode(@json_encode($all_cates)),
                    'all_products' => base64_encode(@json_encode($chu)),
                ];

                $re = curl_post($post_url, $post_data);

                $re = @json_decode($re, true);
                if (isset($re['code']) && $re['code'] == 1) {
                    $success_count = $success_count + $chunk_size;
                }

            } else {

                if ($new_curl > $max_curl) {

                    // 多curl
                    $re_1 = $this->multiCurlPost($curl_data);
                    // var_dump($re_1);

                    // halt($re_1);


                    $new_curl = 0;
                    $curl_data = [];
                } else {
                    $new_curl++;
                    $curl_data[] = [
                        'url' => $post_url,
                        'data' => [
                            'all_cates' => base64_encode(@json_encode($all_cates)),
                            'all_products' => base64_encode(@json_encode($chu)),
                        ]
                    ];
                }

                if ($chu_count == ($k_chu + 1)) {
                    $re_1 = $this->multiCurlPost($curl_data);
                }


            }
        }

        $all_products_count = count($all_products);

        $re = $this->checkWpImprot($info, $all_products_count);

        if (is_array($re)) {
            // 更新出错数据
            $up_list = [];

            foreach ($re as $item) {
                $pro = !empty($all_products[$item['sku']]) ? $all_products[$item['sku']] : [];
                if (!empty($pro)) {
                    $pro['wp_id'] = $item['product_id'];
                    $up_list[] = $pro;
                }
            }

            $this->updateWpData($info, $up_list, $all_cates);

        }


        if ($re == 'success') {
            WebModel::where('id', $info['id'])->update(['status' => 4, 'end_time' => date('Y-m-d H:i:s')]);
            echo '迁移成功';
        } else {
            WebModel::where('id', $info['id'])->update(['status' => 3, 'remark' => '商品迁移失败1', 'end_time' => date('Y-m-d H:i:s')]);
            echo '迁移失败';
        }

        // 记录程序结束时间
        $endTime = microtime(true);
        // 计算执行时间
        $executionTime = $endTime - $startTime;
        // 输出执行时间
        echo "Script execution time: $executionTime seconds";
        die;

    }

    // 检查wordpress导入情况
    public function checkWpImprot($info, $all_products_count)
    {
        // 检查wordpress导入情况
        $check_url = 'https://' . $info['domain'] . '?using_import_product=nNFrUJIh6gmplLMQ&action=check';

        $check_arr = curl_post($check_url, []);

        var_dump($check_arr);

        $check_arr = @json_decode($check_arr, true);

        if (empty($check_arr)) {
            return true;
        }

        $check_list_count = !empty($check_arr['all_product_check']['check_list_count']) ? $check_arr['all_product_check']['check_list_count'] : 0;

        $out_all_product = !empty($check_arr['all_product_check']['out_all_product']) ? $check_arr['all_product_check']['out_all_product'] : [];

        if (!empty($out_all_product) && ($check_list_count == $all_products_count)) {
            // 更新出错数据

            return $out_all_product;
        } else {

            return 'success';
        }


    }

    // 更新wordpress产品数据
    public function updateWpData($info, $update_data, $all_cates)
    {

        $up_url = 'https://' . $info['domain'] . '?using_import_product=nNFrUJIh6gmplLMQ&action=update';

        $chunk_size = 20;

        $update_data_list = array_chunk($update_data, $chunk_size);

        $max_curl = 20;
        $new_curl = 0;

        $curl_data = [];

        $chu_count = count($update_data_list);

        foreach ($update_data_list as $k_chu => $chu) {


            if ($new_curl > $max_curl) {
                $re_1 = $this->multiCurlPost($curl_data);

                $new_curl = 0;
                $curl_data = [];
            } else {
                $new_curl++;
                $curl_data[] = [
                    'url' => $up_url,
                    'data' => [
                        'all_cates' => base64_encode(@json_encode($all_cates)),
                        'all_products' => base64_encode(@json_encode($chu)),
                    ]
                ];
            }

            if ($chu_count == ($k_chu + 1)) {
                $re_1 = $this->multiCurlPost($curl_data);
            }


        }

        return true;

    }

}